package pres.moling.common.http;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class MyHttpClient {
    private static HttpClient client;
    private static HttpRequest.Builder request;
    private static CookieManager cookieManager;


    List<File> files = new ArrayList<>();


    private MyHttpClient() {
        client = HttpClient.newHttpClient();
        request = HttpRequest.newBuilder();
        cookieManager = new CookieManager();
    }

    private MyHttpClient(HttpConnectorConfig connectorConfig) {

    }

    public static MyHttpClient addConfig(HttpConnectorConfig connectorConfig) {
        return Objects.nonNull(connectorConfig) ? new MyHttpClient(connectorConfig) : new MyHttpClient();
    }

    public MyHttpClient addFile(File... files) {
        this.files = List.of(files);
        return this;
    }

    public MyHttpClient get(String url) {
        request.uri(URI.create(url)).GET();
        return this;
    }

    public MyHttpClient post(String url, Map<String, Object> param) {
        request.POST(HttpRequest.BodyPublishers.ofString(JSONObject.toJSONString(param)))
                .uri(URI.create(url));
        return this;
    }

    public MyHttpClient addHeaders(Map<String, String> headers) {
        headers.forEach((k, v) -> request.setHeader(k, v));
        return this;
    }

    public MyHttpClient addHeader(String name, String value) {
        request.setHeader(name, value);
        return this;
    }


    public MyHttpClient addCookies() {
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        return this;
    }

    public String send() {
        try {
            HttpResponse<String> send = client.send(request.build(), HttpResponse.BodyHandlers.ofString());
            return send.body();
        } catch (Exception e) {
            return null;
        }

    }


    /**
     * 发送get
     */
    static String sendGet(String url, Map<String, Object> paramMap) {
        return null;
    }

    static String sendGet(String url) {
        return null;
    }

    static String sendPost(String url, Map<String, Object> paramMap) {

        return null;
    }



}
